import 'package:dio/dio.dart';
import 'package:enjoy_plus_test/utils/http.dart';
import 'package:enjoy_plus_test/utils/toast.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

import '../../utils/eventbus.dart';

class ProfilePage extends StatefulWidget {
  ProfilePage({super.key, required this.userInfo});
  Map userInfo;
  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  Map userInfo = {"avatar": "", "nickName": ""};
  final TextEditingController _avatarControll = TextEditingController();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      userInfo = widget.userInfo;
      _avatarControll.text = userInfo['nickName'];
    });
  }
  updateNickName()async{
    if(_avatarControll.text.isEmpty){
      return ToastUtil.showError('昵称不能为空!');
    }
    try{
      await http.put('/userInfo',data: {
        "nickName":_avatarControll.text
      });
      setState(() {
        userInfo['nickName']=_avatarControll.text;
        ToastUtil.showSuccess('修改成功');
      });
    }catch(e){
      return ToastUtil.showError('$e');
    }
  }
  selectAvatar() {
    // 模态框
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
              height: 200,
              child: Column(children: [
                ListTile(
                  leading: const Icon(Icons.camera_alt),
                  title: const Text('拍照'),
                  onTap: () {
                    // _pickImageFromCamera();
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.photo),
                  title: const Text('相册'),
                  onTap: () {
                    _pickImageFromGallery();
                  },
                )
              ]));
        });
  }
  // 从相册选择图片（兼容 Web 和移动端）

  Future<void> _pickImageFromGallery() async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.gallery);
    if (pickedFile != null) {
      try {
        // FormData formData = FormData.fromMap({
        //   "file": await MultipartFile.fromFile(pickedFile.path),
        //   "type": "avatar",
        // });
        final bytes = await pickedFile.readAsBytes();


        FormData formData = FormData.fromMap({
          "file": MultipartFile.fromBytes(
            bytes,
            filename: 'avatar_${DateTime.now().millisecondsSinceEpoch}.jpg', // 唯一文件名
             // 明确 MIME 类型
          ),
          "type": "avatar",
        });

        var res = await http.post('/upload', data: formData);
        if (res['code'] != 10000) return ToastUtil.showError('上传图片失败!');
        setState(() {
          userInfo['avatar'] = res['data']['url'];
        });
      } finally {
        Navigator.pop(context);
      }
    }
  }
  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,//禁止返回
        child:Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            title: const Text('个人信息'),
            backgroundColor: Colors.transparent,
            centerTitle: true,
            leading: IconButton(onPressed: (){
              eventBus.fire(RefreshMine());
              Navigator.pop(context);
            }, icon: const Icon(Icons.arrow_back),),
          ),
          body: ListView(
            padding: const EdgeInsets.all(10),
            children: [
              SizedBox(
                height: 40,
                child: Row(
                  children: [
                    const Text('头像', style: TextStyle(fontSize: 16)),
                    const Spacer(),
                    GestureDetector(
                      onTap: (){
                        selectAvatar();
                      },
                      child:   Row(
                        children: [
                          ClipRRect(
                            borderRadius: BorderRadius.circular(50.0),
                            child:
                            userInfo['avatar'] != ''
                                ? Image.network(
                              userInfo['avatar'],
                              width: 30,
                              height: 30,
                            )
                                : Image.asset(
                              'assets/images/avatar_1.jpg',
                              width: 30,
                              height: 30,
                            ),
                          ),

                          const Icon(Icons.arrow_forward_ios, size: 12),
                        ],
                      ),
                    )

                  ],
                ),
              ),
              Row(
                children: [
                  Text('昵称'),
                  Spacer(),
                  Expanded(
                    child: TextField(
                      controller:_avatarControll,
                      decoration: InputDecoration(
                        hintText: '请输入昵称',
                        border: InputBorder.none,
                      ),
                      textAlign: TextAlign.right,
                      onEditingComplete: (){
                        updateNickName();
                      },
                    ),
                  ),
                  Icon(Icons.arrow_forward_ios, size: 12),
                ],
              ),
            ],
          ),
        ),
    );

  }
}
